package com.example.sign

import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.SignEntityItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.UiState
import com.example.base.utils.DateTimeUtils
import com.example.sign.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.time.LocalTime


@Route(path = "/sign/SignActivity")
@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding,SignIntent,SignViewModel>() {
    private var mMapView: MapView? = null
    private var mBaiduMap:BaiduMap? = null
    private var mLocationClient:LocationClient? = null
    var inFlag = false//默认未打卡
    var outFlag = false//未打卡
    var signStatus = 1//1正常2迟到 3早退 4缺勤

    var myLocationListener = object:BDAbstractLocationListener(){
        override fun onReceiveLocation(location: BDLocation?) {

            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return
            }

            val locData = MyLocationData.Builder()
                .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.getDirection()).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build()
            mBaiduMap!!.setMyLocationData(locData)
        }

    }
    override fun getLayout(): Int  = R.layout.activity_sign

    override fun getVM(): Class<SignViewModel>  = SignViewModel::class.java

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        mMapView = binding.bmapView
        mBaiduMap = mMapView!!.map
        mBaiduMap?.setMyLocationEnabled(true);


        //定位初始化
        LocationClient.setAgreePrivacy(true)
        mLocationClient = LocationClient(this)


//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps
        option.setCoorType("bd09ll") // 设置坐标类型
        option.setScanSpan(1000)


//设置locationClientOption
        mLocationClient?.setLocOption(option)


//注册LocationListener监听器
        mLocationClient?.registerLocationListener(myLocationListener)

//开启地图定位图层
        mLocationClient?.start()

        //回显打卡记录  判断是否进行了打卡
        val inTime = SPUtils.getInstance().getString("signInTime", "")
        if(inTime.isNotEmpty()){
            //判断是否是今天的打卡时间
            val dateYear = DateTimeUtils.getDateYear()
            val inDate = inTime.substring(0,10)
            Log.d("TAG", "initView: $inDate   $dateYear")
            if(dateYear==inDate){
                binding.tvSigninTime.text = inTime
                inFlag = true

                val outTime = SPUtils.getInstance().getString("signOutTime", "")
                if(outTime.isNotEmpty()){
                    val outDate = outTime.substring(0, 10)
                    if(dateYear==outDate){
                        binding.tvSignoutTime.text = outTime
                        outFlag  = true
                    }
                }
            }
        }

        //点击打卡按钮，根据时间情况，显示正确的打卡时间
        binding.btnSign.setOnClickListener {
            val curTime = DateTimeUtils.getDateTime1()
            val curHour = DateTimeUtils.getTime1()
            val inHour = LocalTime.of(9, 0)
            val outHour = LocalTime.of(18,0)
            if(!inFlag) {
                //未打上班卡
                //判断是否迟到了
                if(LocalTime.parse(curHour).isAfter(inHour)){
                    signStatus = 2
                    binding.tvSigninTime.text = curTime+"  迟到"
                }else{
                    binding.tvSigninTime.text = curTime+"  正常"
                    signStatus = 1
                }
                inFlag = true

                SPUtils.getInstance().put("signInTime",curTime)
            }else{
                //打了上班卡了
                //判断是否打了下班卡
                if(!outFlag){
                    //未打下班卡
                    if(LocalTime.parse(curHour).isAfter(inHour)){
                        if(LocalTime.parse(curHour).isAfter(outHour)){
                            signStatus = 1
                            binding.tvSignoutTime.text = "$curTime  正常"
                        }else{
                            signStatus = 3
                            binding.tvSignoutTime.text = "$curTime  早退"
                        }
                        outFlag = true
                        SPUtils.getInstance().put("signOutTime",curTime)
                    }

                }else{
                    //打了下班卡，再次打卡，更新记录
                    if(LocalTime.parse(curHour).isAfter(outHour)){
                        signStatus = 1
                        binding.tvSignoutTime.text = "$curTime  正常"
                    }else{
                        signStatus = 3
                        binding.tvSignoutTime.text = "$curTime  早退"
                    }

                    SPUtils.getInstance().put("signOutTime",curTime)

                }
            }
            val item = SignEntityItem(
                curTime,
                "lat,lon",
                0,
                "八维培训",
                curTime,
                signStatus.toString(),
                SPUtils.getInstance().getInt("uid"),
                0
            )
            viewModel.sendIntent(SignIntent.sign(item))
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> -> {
                        ToastUtils.showLong("打卡成功")
                    }
                    else->{

                    }
                }
            }
        }

    }
    override fun onResume() {
        super.onResume()

        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView!!.onResume()
    }

    override fun onPause() {
        super.onPause()

        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView!!.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()

        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView!!.onDestroy()
    }

}